import fetchAdapter from '@vespaiach/axios-fetch-adapter'
import axios from 'axios'

export const giteeData = {
  info_url: '', // list info id
}

const request = axios.create({
  adapter: fetchAdapter,
})

const urlCache:string[] = []

// 获取所有文档
export async function getAll () {
  let i = 1
  const tabs = await chrome.tabs.query({ active: true })
  const url = tabs[0].url
  const host = url?.match?.(/(http|https):\/\/\S+?\//)?.[0]
  if (!host) {return}
  const params = url.replace(host, '').split('/')
  const baseURL = host + `${params[0]}/${params[1]}/${params[2]}`
  const list:any = await getWikiList() ?? []
  const sourceList = list?.filter?.((item:any) => !item.isParent)
  for await (const item of sourceList) {
    try {
      const data:any = await new Promise((resolve) => {
        setTimeout(() => {
          const info_id = new URL(giteeData.info_url).searchParams.get('info_id')
          const sourceURL = baseURL + `/pages/wiki?wiki_title=${encodeURI(item.name)}&parent=${item.parent}&version_id=master&sort_id=${item.sort_id}&info_id=${info_id}&extname=.md`
          console.log(sourceURL)
          request.get(sourceURL).then((res) => {
            console.log(res)
            resolve(res.data)
          })
        }, 1000 * Math.random())
      })
      await creatApidoc(data.wiki, baseURL)
    } catch (err) {
      console.log('?????????error', err)
    }
    i++
    console.log(`进度：第${i}个，总共：${sourceList.length}`)
  }
}

//
function creatApidoc (wiki:Record<string, any>, baseURL:string) {
  return new Promise((resolve) => {
    const html = wiki?.content_html
    const router = html?.replace?.(/<.*?>/g, '')?.match?.(/\S+\/\S+/)?.[0]
    console.log({
      name: wiki.id ?? '',
      router: router ?? '',
      link: baseURL + `/${wiki.parent}/${wiki.title}` ?? '',
      desc: wiki.content?.substring(0, 20000) ?? '',
    })
    try {
      request.post('https://socket.worldzb.cn/api/v1/apidoc', {
        name: wiki.id || 'null',
        router: router || 'null',
        link: baseURL + `/${wiki.parent}/${wiki.title}` || 'null',
        desc: wiki.content?.substring(0, 20000) || 'null',
      }).then((res) => {
        resolve(1)
      })
    } catch (err) {
      resolve(1)
    }
  })
}

/**
 * 获取文档列表
 */
export async function getWikiList () {
  return new Promise((resolve) => {
    if (giteeData.info_url) {
      console.log(giteeData.info_url)
      request.get(giteeData.info_url).then((res) => {
        console.log('===', res.data)
        resolve(res.data.msg)
      })
    } else {
      console.log('没有找到项目')
    }
  })
}

export function getWiki (url:string) {
  if (urlCache.indexOf(url) > -1) {return}
  urlCache.push(url)
  request.get(url).then((res) => {
    console.log('===', res.data)
  })
}
